package com.airobot.robot;

import com.airobot.robot.dto.ChatRequest;
import com.airobot.robot.dto.ChatResponse;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "http://localhost:5173")
public class RobotController {

    private final ChatClient chatClient;

    public RobotController(ChatModel chatModel) {
        this.chatClient = ChatClient.builder(chatModel)
                .defaultOptions(DashScopeChatOptions.builder()
                        .withModel("qwen-plus")
                        .withTemperature(0.7)
                        .build())
                .build();
    }

    /**
     * 简单对话接口 - GET版本
     * @param message 用户输入的消息
     * @return 包含AI回复的响应实体
     */
    @GetMapping("/simple")
    public ResponseEntity<ChatResponse> simpleChatGet(@RequestParam String message) {
        try {
            if (message == null || message.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(new ChatResponse("error", "消息不能为空"));
            }

            String response = chatClient.prompt()
                    .user(message)
                    .call()
                    .content();

            ChatResponse chatResponse = new ChatResponse(response);
            return ResponseEntity.ok(chatResponse);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ChatResponse("error", "处理请求时发生错误: " + e.getMessage()));
        }
    }

    /**
     * 简单对话接口 - POST版本（推荐）
     * @param request 包含用户消息的请求体
     * @return 包含AI回复的响应实体
     */
    @PostMapping("/simple")
    public ResponseEntity<ChatResponse> simpleChatPost(@RequestBody ChatRequest request) {
        try {
            if (request.getMessage() == null || request.getMessage().trim().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(new ChatResponse("error", "消息不能为空"));
            }

            String response = chatClient.prompt()
                    .user(request.getMessage())
                    .call()
                    .content();

            ChatResponse chatResponse = new ChatResponse(response);
            return ResponseEntity.ok(chatResponse);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ChatResponse("error", "处理请求时发生错误: " + e.getMessage()));
        }
    }

    /**
     * 健康检查接口
     * @return 服务状态信息
     */
    @GetMapping("/health")
    public ResponseEntity<String> healthCheck() {
        return ResponseEntity.ok("AI ChatBot Service is running properly");
    }
}